﻿namespace Charades.Web.Helpers
{
	using System;
	using System.Drawing;

	public static class ColorHelper
	{
		private static Random _random;

		public static string GenerateColor(ColorFormat format = ColorFormat.Hex)
		{
			_random = new Random();
			var color = ColorFromHsv(_random.Next(0, 360), _random.Next(50, 80)/100.0, 1.0);

			return format == ColorFormat.Hex ?
				string.Format("#{0}{1}{2}", color.R.ToString("X2"), color.G.ToString("X2"), color.B.ToString("X2")) :
				string.Format("rgb({0},{1},{2})", color.R, color.G, color.B);
		}

		private static Color ColorFromHsv(double hue, double saturation, double value)
		{
			var hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6;
			var f = hue / 60 - Math.Floor(hue / 60);

			value = value * 255;
			var v = Convert.ToInt32(value);
			var p = Convert.ToInt32(value * (1 - saturation));
			var q = Convert.ToInt32(value * (1 - f * saturation));
			var t = Convert.ToInt32(value * (1 - (1 - f) * saturation));

			switch (hi)
			{
				case 0:
					return Color.FromArgb(255, v, t, p);
				case 1:
					return Color.FromArgb(255, q, v, p);
				case 2:
					return Color.FromArgb(255, p, v, t);
				case 3:
					return Color.FromArgb(255, p, q, v);
				case 4:
					return Color.FromArgb(255, t, p, v);
				default:
					return Color.FromArgb(255, v, p, q);
			}
		}
	}

	public enum ColorFormat
	{
		Hex,
		Rgb
	}
}
